import axios from 'axios'
import { ElMessageBox, ElMessage } from '@toms/element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router/index'
import { i18n } from '@/lang/index'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60 // request timeout
})

const errorStatuses = [401, 402, 403, 404]

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['WEB-TOKEN'] = getToken()
      config.headers['LANG'] =
        localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
      config.headers['time-zone'] = Intl.DateTimeFormat().resolvedOptions().timeZone
      config.headers['platCode'] = 'PASS'
    }
    if (config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              const params = propName + '[' + key + ']'
              var subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    return res
  },
  (error) => {
    if (error.response != null) {
      const status = error.response.status
      const { traceId, code } = error.response.data
      if (status === 401) {
        store.dispatch('user/resetToken').then(() => {
          ElMessage({
            message: 'You have been logged out,please log in again',
            type: 'error',
            duration: 5 * 1000
          })
        })
        router.replace('/login')
        return
      }
      let errorMessage
      if (error.response.data.message) {
        errorMessage = error.response.data.message
      } else {
        errorMessage = error.message
      }

      // 参数错误提示特殊处理
      if (status === 501) {
        if (error.response.data.message) {
          const paramResp = JSON.parse(error.response.data.message)
          errorMessage = paramResp.msg || paramResp.message
          // 特殊处理，后面2.1重构好要去除
          if (errorMessage.indexOf('task [] in plan mode') > 0) {
            errorMessage = errorMessage.replace('task [] in plan mode', 'a update schedule')
          }
        } else {
          errorMessage = error.message
        }
      }

      if (status >= 500) {
        ElMessageBox .confirm(
          `<div class="content">${errorMessage}</div><p class="error__message">Error code: ${
            code + '-' || ''
          }${traceId || ''}</p>`,
          'Error',
          {
            confirmButtonText: 'OK',
            showCancelButton: false,
            type: 'error',
            center: false,
            dangerouslyUseHTMLString: true
          }
        )
        if (status !== 501) { return new Promise(() => {}) }
      } else if (errorStatuses.includes(status)) {
        // ElMessage({
        //   message: errorMessage,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        return new Promise(() => {})
      }
    } else if (error.message.indexOf('timeout') !== -1) {
      ElMessage({
        message: i18n.t('common.time_out'),
        type: 'error',
        duration: 5 * 1000
      })
      error.timeout = true
    }
    return Promise.reject(error.response ? error.response.data : error)
  }
)

export default service
